<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <title>Game</title>
  <%= stylesheet_link_tag 'game' %>
  <%= javascript_include_tag 'jquery-1.2.6.min.js' %>
  <%= javascript_include_tag 'json2.js' %>
  <%= javascript_include_tag 'jquery.timers-1.1.3.js' %>
</head>
<body>

<p style="color: green"><%= flash[:notice] %></p>

<script type="text/javascript">

jQuery(document).ready(function () {
(function ($) {

var Requester = function () {}
Requester.prototype = {
	send: function (action, resource, params) {
		if (params == null) params = {};
		
		this.response = $.ajax({
			method: 'GET',
			async: false,
			url: '?',
			data: {
				format: 'json',
				request: JSON.stringify({
					'action': action,
					'resource': resource,
					'params': params,
				}),
			},
			
		}).responseText;
	},
	
	getJSONResponse: function () {
		return JSON.parse(this.response);
	},
	
	getResponse: function () {
		return this.response;
	},
}

function Game () {
	this.req = new Requester;
	this.client = this.req;
	this.hand = new Array;
	
	this.client.send('GET', 'player/id');
	this.me = this.client.getJSONResponse().player.id;
}

Game.prototype = {
	load_hand: function () {
		var client = this.req;
		
		$('#hand').each (function () {
			$(this).text('');
			
			$(this).append(
				$('<div/>').addClass('card').addClass('playable').click(function () {
					client.send('PUT', 'player/draw');
					var response = client.getJSONResponse();
				})
			);
			
			client.send('GET', 'player/cards');
			var response = client.getJSONResponse();
			
			for each(c in response.player.cards) {
				$(this).append(Card(c, {playable:true, 'client':client}));
			}
		});
	},
	
	load_players: function () {
		var client = this.req;
		var me = this.me;
		
		$('#players').each (function () {
			$(this).text('');
			
			var table = $('<table></table>');
			$(this).append(table);
			
			client.send('GET', 'player/cards');
			var hand = client.getJSONResponse().player.cards;
			
			client.send('GET', 'game/players/nb_cards');
			var response = client.getJSONResponse();
			for each(p in response.game.players) {
				var td_content = function (n) {
					var td = $('<td/>');
					
					if (p.id == me) {
						for each(c in hand) {
							var card = Card(c);
							card.removeClass('card').addClass('littlecard').text('');
							td.append(card);
						}
					} else {
						for (i = 0; i < n; i += 1) {
							td.append('<div class="littlecard"></div>');
						}
					}
					
					return td;
				}
				var tr = $('<tr/>')
					.append($('<td/>').append(''+p.id))
					.append($('<td/>').append(td_content(p.nb_cards)));
				table.append(tr);
			}
		});
		
		this.update_turn();
	},
	
	update_turn: function () {
		this.client.send('GET', 'game/turn');
		var turn = this.client.getJSONResponse().game.turn;
		
		$('#players tr').each(function (i) {
			if (turn == i) {
				$(this).addClass('current');
			} else {
				$(this).removeClass('current');
			}
		});
	},
	
	update_players: function () {
		
	},
	
	load_top_discard: function () {
		var client = this.req;
		
		$('#top_discard').each (function () {
			$(this).text('');
			
			client.send('GET', 'game/discard/top');
			var card = Card(client.getJSONResponse().game.discard.top);
			card.addClass('top_discard');
			$(this).append(card);
		});
	},
	
	update_after_self_draw: function () {
		var client = this.req;
		
		$('#hand').each (function () {
			var old_length = $(this).find('.card').size();
			
			client.send('GET', 'player/cards');
			var hand = client.getJSONResponse().player.cards;
			
			var diff = hand.length - old_length;
			
			for (var i = hand.length - 2; i < hand.length; i += 1) {
				$(this).append(Card(hand[i], {playable:true, 'client':client}));
			}
		});
	},
	
	update_after_playing: function (card) {
		$('#hand .card').each (function () {
			//~ $('#trash').append('[text:' + $(this).find('.data').text() + ', card: ' + card + ']');
			
			if ($(this).find('.data').text() == card) {
				//~ $('#trash').append(this);
				$(this).remove();
				return false;
			}
		});
	},
}

function Card(str, options) {
	var car = str;
	var div = $('<div/>').addClass('card');
	
	if (str[0].match(/[ABCD]/)) {
		div.addClass(str[0])
		car = str[1];
		if (str[2] != undefined) car += (str[2]);
	}
	
	if (str[0].match(/[EJ]/)) {
		div.addClass(str[0]);
	}
	
	if (str.match(/\+4/)) {
		div.addClass('w4');
	}
	
	div.text(car);
	div.append($('<span/>').text(str).addClass('data'));
	
	if (options && options.playable) {
		div.click(function () {
			var client = options.client;
			client.send('PUT', 'player/play', {'card': str});
		});
		div.addClass('playable');
	}
	
	return div;
}

var game = new Game();

(function () {
	$('<ul/>').appendTo($('#log'));
	var client = new Requester;
	var last_update = -1;
	
	var lambda = function(i) {
		client.send('GET', 'messages', {'start':last_update + 1});
		var log =$($('#log ul'));
		var update_hand = false;
		
		//~ process_message = function (e) {
			//~ var li = $('<li/>');
			//~ for each(w in e.message.split(' ')) {
				//~ li.append(w);
			//~ }
			//~ return li;
		//~ }
		
		each_message = function (callback) {
			for each(e in client.getJSONResponse().messages) {
				last_update = e.id;
				
				var li = $('<li/>');
				for each(w in e.message.split(' ')) {
					if (m = w.match(/\[([ABCD])([0-9SR]|\+2)\]/)) {
						li.append($('<span/>').addClass(m[1]).text(m[2]));
					} else if (w == '[+4]') {
						li.append($('<span/>').addClass('w4').text('+4'));
					} else if (w == '[J]') {
						li.append($('<span/>').addClass('J').text('J'));
					} else {
						li.append(w + ' ');
					}
				}
				log.prepend(li);
				
				if (callback != null)
					callback(e);
			}
		}
		
		if (last_update == -1) {
			each_message();
			//~ for each(e in client.getJSONResponse().messages) {
				//~ log.append(process_message(e));
			//~ }
			
		} else {
		
			//~ for each(e in client.getJSONResponse().messages) {
				//~ log.append(process_message(e));
			each_message(function (e) {
				//~ if (e.message.match(/^You tried to play \[.+\] but fails\.$/)) {
					//~ game.update_after_self_draw();
				//~ }
				
				if (e.message.match(/^\[Player .+\] tried to play \[.+\] but fails\.$/)) {
					game.update_players();
				}
				
				if (e.message.match(/^\[Player .+\] played \[.+\]\.$/)) {
					game.load_top_discard();
					game.update_turn();
				}
				
				if (m = e.message.match(/^You played \[(.+)\]\.$/)) {
					game.load_top_discard();
					game.update_turn();
					game.update_after_playing(m[1]);
				}
				
				if (e.message.match(/^You draw .+/)) {
					game.update_after_self_draw();
					game.update_turn();
				}
			});
		}
		
		//~ if (refresh) {
			//~ game.load_hand();
			//~ game.load_players();
			//~ game.load_top_discard();
		//~ }
		
	}
	lambda();
	$(document).everyTime(100, lambda);
})();

game.load_hand();
game.load_players();
game.load_top_discard();

})(jQuery);
});

</script>

<div id="players"></div>
<div id="log"></div>
<div id="top_discard"></div>
<div id="hand"></div>
<div id="trash"></div>

</body>
</html>
